<template>
  <el-row style="height: 100vh">
<!--    <el-col :span="4"-->
<!--            style="height: 100%;padding-left: 10px;padding-top: 20px;border-right: 1px solid #dfe6ec;display: block;overflow-y: scroll;">-->
<!--&lt;!&ndash;      <div class="comp-tree">&ndash;&gt;-->
<!--&lt;!&ndash;        <el-input placeholder="输入关键字进行过滤~" v-model="filterText"></el-input>&ndash;&gt;-->
<!--&lt;!&ndash;        <el-tree class="filter-tree"&ndash;&gt;-->
<!--&lt;!&ndash;                 default-expand-all&ndash;&gt;-->
<!--&lt;!&ndash;                 :filter-node-method="filterNode"&ndash;&gt;-->
<!--&lt;!&ndash;                 ref="SlotTree"&ndash;&gt;-->
<!--&lt;!&ndash;                 :default-expanded-keys="treeData"&ndash;&gt;-->
<!--&lt;!&ndash;                 :current-node-key="currentNodekey"&ndash;&gt;-->
<!--&lt;!&ndash;                 :data="treeList"&ndash;&gt;-->
<!--&lt;!&ndash;                 :props="defaultProps"&ndash;&gt;-->
<!--&lt;!&ndash;                 :expand-on-click-node="false"&ndash;&gt;-->
<!--&lt;!&ndash;                 highlight-current&ndash;&gt;-->
<!--&lt;!&ndash;                 :node-key="NODE_KEY" @node-click="handleNodeClick">&ndash;&gt;-->
<!--&lt;!&ndash;          <template v-slot="{ node, data }">&ndash;&gt;-->
<!--&lt;!&ndash;            <el-tooltip :content="data.label" placement="top">&ndash;&gt;-->
<!--&lt;!&ndash;              <span>{{ data.label }}</span>&ndash;&gt;-->
<!--&lt;!&ndash;            </el-tooltip>&ndash;&gt;-->
<!--&lt;!&ndash;          </template>&ndash;&gt;-->
<!--&lt;!&ndash;        </el-tree>&ndash;&gt;-->
<!--&lt;!&ndash;      </div>&ndash;&gt;-->
<!--    </el-col>-->
    <el-col :span="24">
        <div ref="graphContainer" id="DataLineageGraphContainer" style="width: 100%; height: 100vh;position: relative;">
          <el-row :span="24">
            <el-col :span="6" style="position: absolute;top: 20px;left: 20px;">
              <el-select
                v-model="adCode"
                clearable
                placeholder="请选择"
                @clear="handleClear"
                ref="selectUpResId"
              >
                <el-option hidden  :value="adCode" :label="upResName">
                </el-option>
                <el-tree
                  :data="treeList"
                  :props="treeProps"
                  :expand-on-click-node="false"
                  :check-on-click-node="true"
                  @node-click="handleNodeClick"
                >
                </el-tree>
              </el-select>
<!--              <el-select v-model="value" placeholder="请选择" size="small" style="margin-top: 5%">-->
<!--                <el-option-->
<!--                  v-for="item in options"-->
<!--                  :key="item.value"-->
<!--                  :label="item.label"-->
<!--                  :value="item.value">-->
<!--                </el-option>-->
<!--              </el-select>-->
            </el-col>

          </el-row>
        </div>
    </el-col>
    <el-drawer
      :title="openTableTitle"
      :visible.sync="nodeDrawer"
      :direction="direction"
      size="35%"
      :before-close="closeNodeDraw">
      <el-table :data="entityInfoList" style="  border: 1px dashed #BBB;">
        <el-table-column property="id" label="id" width="150" v-if="false"></el-table-column>
        <el-table-column property="tableName" label="表名" width="100"></el-table-column>
        <el-table-column property="columnComment" label="中文名" width="100"></el-table-column>
        <el-table-column property="dataType" label="数据类型" ></el-table-column>
        <el-table-column property="relation" label="关联字典表/字段"  ></el-table-column>
        <el-table-column property="valueBz" label="值域标识" ></el-table-column>
      </el-table>
    </el-drawer>
  </el-row>

</template>
<style scoped>
#DataLineageGraphContainer {

  background-image: url('../../assets/dataRelationBg.png'); /* 设置背景图像的 URL */
  background-size: cover; /* 控制背景图像的尺寸适应容器 */
  /*background-repeat: repeat;*/
  /* 其他背景样式属性，如背景颜色、重复方式等 */
}
/* 自定义节点的样式 */
.el-tree-node__content:hover {
  background-color: #e0e0e0;
  cursor: pointer;
}

/* 自定义工具提示的样式 */
.el-tooltip__popper {
  z-index: 9999; /* 确保工具提示显示在顶部 */
}

#treeBox {
  margin-top: 1px;

.el-table thead {
  display: none;
}

}
.span {
  color: #606266;
  font-weight: 700;
  font-size: 14px;
}
</style>
<script>
import { deletecolumn, exportcolumn, updatecolumn } from '@/api/metadata/column'
import Import from '@/components/Import/import'
import waves from '@/directive/waves'
import permission from '@/directive/permission/permission'
import Pagination from '@/components/Pagination'
import { getModelTree,getFieldRelation } from '@/api/metadata/label/metadataLabel'
import { getStatsListByAd,getAdInfo,getInfoListByEntityAd } from '@/api/dataLineage/dataLineage'
import G6 from "@antv/g6";
import {fetchMasterdataDirectoryList} from "@/api/masterdata/masterdataDirectory";

export default {
  name: "DataLineageRelation",
  directives: {waves, permission},
  mounted() {
    this.initGraph()
  },
  data() {
    return {
      entityInfoList:[],
      edgesRelation:{},
      openTableTitle:'',
      nodeTableInfo:[],
      edgeInfo:[],
      nodeDrawer: false,
      edgeDrawer: false,
      direction: 'rtl',
      adCode:'370000000000',
      upResName:'',
      treeProps: {
        children: 'children',
        label: 'name'
      },
      options: [],
      value: '',
      filterText: '',
      tableKey: 0,
      treeList: [],
      query:{
        adCode:'',
        entityCode:''
      },
      labelList: [],
      list: null,
      total: 0,
      multipleSelection: [],
      downloadLoading: false,
      listLoading: true,
      pageArray: this.$store.getters.pageArray,
      listQuery: {
        columnName: undefined,
        ancestralId: '4',
        page: 1,
        limit: this.$store.getters.defaultPageSize
      },
      entityQuery: {},
      currentNodekey: '',
      treeData: [],
      defaultProps: {// 默认设置
        children: 'children',
        label: 'name'
      },
      NODE_KEY: 'id',
      defaultNode: [],
      nodes: [],
      edges: [],
      graph: null,
    }
  },
  computed: {
    ids() {
      const ids = []
      this.multipleSelection.forEach(ele => {
        ids.push(ele.id)
      })
      return ids.join(',')
    }
  },
  created() {
    const defaultNode = {
      id: '370000000000',
      size: 80,
      label: '山东省',
      description:'山东省'
    }
    this.defaultNode = defaultNode;
    this.nodes.push(defaultNode);

    this.getRelation();
    this.getAdInfoForPage();
  },
  watch: {
    filterText(val) {
      this.$refs.SlotTree.filter(val);
    }
  },
  methods: {
    initGraph() {
      const container = this.$refs.graphContainer;
      const width = container.offsetWidth;
      const height = container.offsetHeight;

      this.graph = new G6.Graph({
        container,
        width,
        height,
        fitCenter: true,
        layout: {
          type: 'concentric',
          preventOverlap: true,
          linkDistance: 500, // 设置节点之间的距离
          nodeStrength: 500, // 节点之间的吸引力
          edgeStrength: 0.1, // 边之间的斥力
          minMovement: 0.001, // 布局运动的最小阈值
          nodeSpacing:100,
          // 其他布局参数...
          minComboEdgeDistance: 10, // 设置组合节点之间的最小边距
          focusNode: '370000000000', // 设置一个焦点节点
        },
        modes: {
          default: ['drag-canvas', 'drag-node']
        },
        defaultNode: {
          type: 'circle',
          size: [60],
          labelCfg: {
            position: 'bottom',
          },
          linkPoints: {
            top: true,
            right: true,
            bottom: true,
            left: true,
          },
          /* icon configuration */
          icon: {
            /* whether show the icon, false by default */
            show: true,
            /* icon's img address, string type */
            // img: 'https://gw.alipayobjects.com/zos/basement_prod/012bcf4f-423b-4922-8c24-32a89f8c41ce.svg',
            /* icon's size, 20 * 20 by default: */
            //   width: 40,
            //   height: 40
          },
        },
        nodeStateStyles: {
          hover: {
            fill: 'blue',
          },
        },

      });
      this.graph.on('node:dragstart', function (e) {
        this.graph.layout();
        refreshDragedNodePosition(e);
      });
      this.graph.on('node:drag', function (e) {
        refreshDragedNodePosition(e);
      });
      this.graph.on('node:dragend', function (e) {
        e.item.get('model').fx = null;
        e.item.get('model').fy = null;
      });
      this.graph.on('node:click', (evt) => {
        const node = evt.item; // 获取被点击的节点
        console.log('Node clicked:', node.getModel());
        this.query.entityCode= node.getModel().id
        this.query.adCode= this.adCode
        this.getInfoListByAd(this.query)
        this.nodeDrawer = true;
      });
      if (typeof window !== 'undefined')
        window.onresize = () => {
          if (!this.graph || this.graph.get('destroyed')) return;
          if (!container || !container.scrollWidth || !container.scrollHeight) return;
          graph.changeSize(container.scrollWidth, container.scrollHeight);
        };

      function refreshDragedNodePosition(e) {
        const model = e.item.get('model');
        model.fx = e.x;
        model.fy = e.y;
      }

      this.graph.render();
    },
    closeNodeDraw(done) {
      done();
    },
    handleClear() {
      // 将选择器的值置空
      this.upResName = ''
      this.adCode  = ''
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    handleNodeClick(val) {
      console.log(JSON.stringify(val))
      const defaultNode = {
        id: val.code,
        size: 80,
        label: val.name,
        description:val.name
      }
      this.defaultNode = defaultNode;
      // console.log("修改后的===="+JSON.stringify(this.defaultNode))
      this.adCode = val.code
      this.nodes=[];
      this.edges=[];

      this.getRelation('update')
    },
    getTreeList() {
      this.listLoading = true
      getModelTree(this.listQuery).then(response => {
        if (response.data.code === 0) {
          this.treeList = response.data.data
          this.listLoading = false
          // this.$refs.form.setList(this.treeList)
        } else {
          this.$message.error(response.data.msg)
        }
        this.listLoading = false
      })
    },
    getLabelList() {
      this.listLoading = true
      fetchMetadataLabelGroupList(this.listQuery).then(response => {
        if (response.data.code === 0) {
          this.labelList = response.data.data
          this.listLoading = false
          this.$refs.form.setList(this.labelList)
        } else {
          this.$message.error(response.data.msg)
        }
        this.listLoading = false
      })
    },
    //编辑实体按钮
    handleEdit() {
      if (this.listQuery.sourceId) {
        this.entityQuery.tableId = this.listQuery.sourceId
        this.$refs.entityform.handleUpdate()
        this.$refs.entityform.setList(this.entityQuery)
      } else {
        this.$message.warning('请先选择表')
      }
    },
    //定义实体按钮
    handleCreate() {
      if (this.listQuery.sourceId) {
        this.entityQuery.tableId = this.listQuery.sourceId
        this.$refs.entityform.setList(this.entityQuery)
        this.$refs.entityform.handleCreate()
      } else {
        this.$message.warning('请先选择表')
      }
    },
    //查看实体按钮
    handleCheck() {
      if (this.listQuery.sourceId) {
        this.entityQuery.tableId = this.listQuery.sourceId
        this.$refs.entityList.setList(this.entityQuery)
        this.$refs.entityList.handleCheck()
      } else {
        this.$message.warning('请先选择表')
      }

    },
    load(tree, treeNode, resolve) {
      resolve(tree.children)
    },
    getListByTreeId(data) {

    },
    getAdInfoForPage(){
      this.upResName = '山东省';
      this.listLoading = true
      getAdInfo().then(response => {
        if (response.data.code == 200) {
          // console.log("获取到的行政区划信息="+JSON.stringify(response.data.data))
          var arr = [];
          arr.push(response.data.data)
          // console.log("获取到的行政区划信息="+JSON.stringify(arr))
          this.treeList = arr
          if(this.treeList.length>0){
            this.listQuery.directoryId = this.treeList.code
            this.currentNodekey = this.treeList.code;
            this.$nextTick(() => {
              this.$refs.SlotTree.setCurrentKey(this.currentNodekey); //一定要加这个选中了否则样式没有出来
            });
          }
          this.listLoading = false
        } else {
          this.$message.error(response.data.msg)
        }
        this.listLoading = false
      })
    },
    getInfoListByAd(data){
      this.listLoading = true
      getInfoListByEntityAd(this.query).then(response => {
        if (response.data.code == 200) {

          for(var i=0;i<response.data.data.length;i++){
            this.entityInfoList.push(response.data.data[i].n)

          }
          this.listLoading = false
        } else {
          this.$message.error(response.data.msg)
        }
        this.listLoading = false
      })
    },
    getRelation(type) {
      // if(!this.listQuery.sourceId){
      //   this.$message.error("请选择一个数据表")
      //   return;
      // }
      // alert(this.adCode)
      this.nodes=[];
      this.edges=[];
      this.nodes.push(this.defaultNode);
      this.listLoading = true
      getStatsListByAd({adCode: this.adCode}).then(response => {
        console.log("获取到的血缘信息="+JSON.stringify(response.data.data))
        this.list = response.data.data
        let nodeObj
        for (var i = 0; i < this.list.length; i++) {
          let nodeObj = {
            id: this.list[i].entityCode,
            size: 80,
            label: this.list[i].name
          }
          let edgeObj = {
            source: this.defaultNode.id,
            target: this.list[i].entityCode,
            description:'山东省'
          }

          this.nodes.push(nodeObj)
          this.edges.push(edgeObj)
        }
        if(type === 'update'){

          this.updateNodes();
        }else{
          this.setNodes();
        }

        // this.total = response.data.total
        // this.setSort()
        this.listLoading = false
      })
      //
      // getFieldRelation({modelId: '1'}).then(response => {
      //   this.list = response.data.data
      //   let nodeObj
      //   for (var i = 0; i < this.list.records.length; i++) {
      //     // { id: 'node15', size: 40, isLeaf: true },
      //     // { source: 'node0', target: 'node3' },
      //     nodeObj = {
      //       id: this.list.records[i].primaryTableid,
      //       size: 80,
      //       label: this.list.records[i].primaryTablename
      //     }
      //
      //     let nodeObj2 = {
      //       id: this.list.records[i].secondaryTableid,
      //       size: 80,
      //       label: this.list.records[i].secondaryTablename
      //     }
      //     let edgeObj = {
      //       source: this.list.records[i].primaryTableid,
      //       target: this.list.records[i].secondaryTableid
      //     }
      //
      //     this.nodes.push(nodeObj2)
      //     this.edges.push(edgeObj)
      //   }
      //   this.nodes.push(nodeObj)
      //   this.setNodes();
      //
      //   // this.total = response.data.total
      //   // this.setSort()
      //   this.listLoading = false
      // })
    },
    handleUpdate(row) {
      this.$refs.form.setList(this.labelList)
      this.$refs.form.handleUpdate(row.id)
    },
    handleUpdate1(row) {
      this.$confirm('确定解除标签绑定吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = row
        data.labelId = ''
        updatecolumn(data).then(response => {
          this.loading = false
          if (response.data.code === 0) {
            this.dialogFormVisible = false
            this.getRelation()
            this.$message.success(response.data.msg)
          } else {
            this.$message.error(response.data.msg)
          }
        })
      })
    },
    handleDelete(row) {
      this.$confirm('确定删除该数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletecolumn(row.id).then(response => {
          if (response.data.code === 0) {
            this.getRelation()
            this.$message.success(response.data.msg)
          } else {
            this.$message.error(response.data.msg)
          }
        })
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleBathDelete() {
      if (this.ids === '') {
        this.$message.warning('请选择至少一条数据')
        return
      }
      this.$confirm('确定删除所选数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletecolumn(this.ids).then(response => {
          if (response.data.code === 0) {
            this.getRelation()
            this.$message.success(response.data.msg)
          } else {
            this.$message.error(response.data.msg)
          }
        })
      })
    },
    handleImport() {
      this.$refs.import.show()
    },
    handleExport() {
      if (this.ids === '') {
        this.$message.warning('请选择至少一条数据')
        return
      }
      this.downloadLoading = true
      exportcolumn(this.ids).then(response => {
        this.downloadLoading = true
        if (response.data.code === 0) {
          import('@/vendor/Export2Excel').then(excel => {
            excel.export_byte_to_excel(response.data.data.bytes, response.data.data.title)
            this.downloadLoading = false
          })
        } else {
          this.$message.error(response.data.msg)
        }
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getRelation()
    },
    setNodes() {
      const data = {
        nodes: this.nodes,
        edges: this.edges,
      };
      const nodes = data.nodes;
      this.graph.data({
        nodes,
        edges: data.edges.map(function (edge, i) {
          edge.id = 'edge' + i;
          return Object.assign({}, edge);
        }),
      });
      this.graph.render();

      // this.graph.on('node:dragstart', function (e) {
      //   this.graph.layout();
      //   refreshDragedNodePosition(e);
      // });
      // this.graph.on('node:drag', function (e) {
      //   refreshDragedNodePosition(e);
      // });
      // this.graph.on('node:dragend', function (e) {
      //   e.item.get('model').fx = null;
      //   e.item.get('model').fy = null;
      // });
      // this.graph.on('node:click', (evt) => {
      //   const node = evt.item; // 获取被点击的节点
      //   console.log('Node clicked:', node.getModel());
      //   this.query.entityCode= node.getModel().id
      //   this.query.adCode= this.adCode
      //   this.getInfoListByAd(this.query)
      //   this.nodeDrawer = true;
      // });
      // if (typeof window !== 'undefined')
      //   window.onresize = () => {
      //     if (!this.graph || this.graph.get('destroyed')) return;
      //     if (!container || !container.scrollWidth || !container.scrollHeight) return;
      //     graph.changeSize(container.scrollWidth, container.scrollHeight);
      //   };
      //
      // function refreshDragedNodePosition(e) {
      //   const model = e.item.get('model');
      //   model.fx = e.x;
      //   model.fy = e.y;
      // }

      this.graph.data(data);
      this.graph.render();
    },
    updateNodes() {
      const data = {
        nodes: this.nodes,
        edges: this.edges,
      };
      const nodes = data.nodes;
      this.graph.data({
        nodes,
        edges: data.edges.map(function (edge, i) {
          edge.id = 'edge' + i;
          return Object.assign({}, edge);
        }),
      });
      this.graph.render();


      this.graph.changeData(data);
      this.graph.render();
    }
  }
}
</script>

<style scoped>

</style>
